package com.zkjl.protect_business.init;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.github.javafaker.Faker;
import com.google.common.collect.Lists;
import com.zkjl.protect_business.common.BaseException;
import com.zkjl.protect_business.config.RbacAuthorityService;
import com.zkjl.protect_business.dto.OrganizationDTO;
import com.zkjl.protect_business.dto.PermissionDTO;
import com.zkjl.protect_business.dto.businessType.BusinessDTO;
import com.zkjl.protect_business.entity.*;
import com.zkjl.protect_business.repository.BusinessRepository;
import com.zkjl.protect_business.repository.PermissionRepository;
import com.zkjl.protect_business.repository.SysRoleRepository;
import com.zkjl.protect_business.repository.UserRepository;
import com.zkjl.protect_business.service.BusinessService;
import com.zkjl.protect_business.service.OrganizationService;
import com.zkjl.protect_business.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.elasticsearch.UncategorizedElasticsearchException;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.zkjl.protect_business.common.Consts.ADMIN;
import static com.zkjl.protect_business.common.Consts.PERSON_DOCUMENT;


/**
 * 系统初始化类
 */
@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {

    @Autowired
    UserRepository userRepository;
    @Autowired
    SysRoleRepository roleRepository;
    @Autowired
    PermissionRepository permissionRepository;

    @Autowired
    BusinessRepository businessRepository;
    @Autowired
    RbacAuthorityService rbacAuthorityService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    BusinessService businessService;

    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    OrganizationService organizationService;

    @Value(value = "${org.name}")
    private String orgName;


    private Digester md5 = new Digester(DigestAlgorithm.MD5);

    private static Faker faker = new Faker(Locale.CHINA);
    public static  String[] dd = new String[]{"上海","北京","成都","天津"};

    @Override
    public void run(ApplicationArguments args) throws Exception {

//        initPermission();

        initBusiness();

        initPermissionCustom();

        String orgId = initOrg();

        initUser(orgId);
        checkJDXZ();
        initializeDefaultIndex();

        initBusinessSort();
    }


    /**
     * 检查是否存在军地协作
     */
    public void checkJDXZ() {

        Business byName = null;
        try {
            byName = businessService.getByName(PERSON_DOCUMENT);
        } catch (BaseException e) {
            log.error("找军地协作失败，自动创建",e);
            cretaJDXZ();
        }



    }


    /**
     * 初始化业务排序，只要有一个业务没有排序就要初始化
     */
    public void initBusinessSort() {

        List<Business> list = businessService.list();
        List<Business> collect = list.stream().filter(business -> business.getSort() == null).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return;
        }
        log.info("存在未排序的业务，初始化所有业务排序");

        AtomicInteger sort = new AtomicInteger();
        //先排序第一级
        list.stream().filter(business -> StringUtils.isEmpty(business.getPid())).forEach(business -> {
            int andIncrement = sort.getAndIncrement();
            business.setSort(andIncrement);
            businessRepository.save(business);
            updateSort(business.getId());
        });

    }


    /**
     * 修改下级排序
     * @param id
     */
    public void updateSort(String id) {

        AtomicInteger sort = new AtomicInteger();
        List<Business> businesses = businessRepository.findAllByPid(id);
        if (CollUtil.isNotEmpty(businesses)) {

            businesses.stream().forEach(business -> {
                int andIncrement = sort.getAndIncrement();
                business.setSort(andIncrement);
                businessRepository.save(business);
                updateSort(business.getId());

            });
        }

    }


    /**
     * 初始化自定义业务的默认索引
     */
    public void initializeDefaultIndex() {

        log.info("更新自定义业务索引......");
        //获取所有自定义的业务(有字段定义的业务)
        List<Business> list = businessService.list();
        list.stream().filter(business -> {
            List<BusinessField> fields = business.getFields();
            return CollUtil.isNotEmpty(fields);
        }).forEach(business -> {


            String name = business.getName();
            String pname = business.getPname();
            List<BusinessField> fields = business.getFields();
            try {
                businessService.creatIndex(fields,name,pname);
            } catch (UncategorizedElasticsearchException e) {
                log.error("更新索引出错:{}", e.getMessage());
                log.info("开始重建索引.....");
                IndexCoordinates index = businessService.getIndex(business.getId());
                businessService.updateIndex(fields, index);
            }

        });
        log.info("更新自定义业务索引完成");

    }

    /**
     * 初始化机构信息
     */
    private String  initOrg() {

        List<Organization> list = organizationService.list();
        if (!CollUtil.isEmpty(list)) {
            return "";
        }

        log.info("初始化基础单位信息");

        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setOrgName("总部");
        if (StringUtils.isBlank(orgName)) {
            organizationDTO.setOrgName("orgName");
        }

        organizationDTO.setOrgNum("0001");
        Organization organization = organizationService.saveOrUpdate(organizationDTO, null);
        String id = organization.getId();

        //创建几个子机构
        creatOrg("集团军1", id);
        creatOrg("集团军2", id);
        creatOrg("集团军3", id);
        creatOrg("集团军4", id);
        creatOrg("集团军5", id);
        creatOrg("集团军6", id);
        creatOrg("集团军7", id);
        creatOrg("集团军8", id);
        creatOrg("集团军9", id);
        creatOrg("集团军10", id);
        log.info("基础单位信息初始完成");
        return id;

    }

    /**
     * 创建子单位
     * @param name
     * @param pid
     */
    private void creatOrg(String name,String pid) {
        OrganizationDTO organizationDTO2 = new OrganizationDTO();
        organizationDTO2.setOrgName(name);
        organizationDTO2.setPid(pid);
        organizationDTO2.setRegion(RandomUtil.randomEle(dd));
        organizationService.saveOrUpdate(organizationDTO2, null);
    }


    /**
     * 初始化业务
     */
    public void initBusiness() {

        //判定当前系统是否有业务分类，没有的话就创建
        Iterable<Business> all = businessRepository.findAll();
        if (CollUtil.isNotEmpty(all)) {
            return;
        }
        log.info("初始化业务系统");

        List<BusinessDTO> list = new ArrayList<>();
        list.add(cretaBusiness("政治考核", ""));
        list.add(cretaGBRY());
        list.add(cretaXLCS());
        list.add(cretaFXRY());
        list.add(cretaWLWG());
        list.add(cretaZSWT());
        list.add(cretaXSAJ());
        addbBsiness("专项任务", list);

        List<BusinessDTO> yinmi = new ArrayList<>();
        yinmi.add(cretaBusiness("敌情社情", ""));
        addbBsiness("隐蔽斗争", yinmi);

        List<BusinessDTO> list1 = new ArrayList<>();
        list1.add(cretaZJGG());
        addbBsiness("专家骨干", list1);

        List<BusinessDTO> yewu = new ArrayList<>();
        yewu.add(cretaBusiness("业务培训", ""));
        addbBsiness("业务培训", yewu);

        List<BusinessDTO> list2 = new ArrayList<>();
        list2.add(cretaTXL());
        list2.add(cretaBusiness("视频指挥", ""));
        list2.add(cretaBusiness("文件通知", ""));
        addbBsiness("通信联络", list2);

        List<BusinessDTO> list3 = new ArrayList<>();
        list3.add(cretaZYMB());
        list3.add(cretaRYDA());
        list3.add(cretaBusiness("单位信息", ""));
        list3.add(cretaBusiness("常用模板", ""));
        addbBsiness("基础信息", list3);


        List<BusinessDTO> list4 = new ArrayList<>();
        list4.add(cretaBusiness("站内搜索", ""));
        list4.add(cretaBusiness("云搜索", ""));
        addbBsiness("内容搜索", list4);
        log.info("初始化业务系统完成");

    }

    /**
     * 政治考核
     * @return
     */
    public BusinessDTO cretaZZKH() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("政治考核人员详情");
        businessDTO.setRouting("");

        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("考核结果", "string", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("单位", "string", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("军衔", "string", fields);
        creatBusinessField("函调表", "string", fields);
        creatBusinessField("查阅档案资料记录表", "string", fields);
        creatBusinessField("谈话记录", "string", fields);
        creatBusinessField("民主测评表", "string", fields);
        creatBusinessField("背景审查登记表", "string", fields);
        creatBusinessField("背景核查报告", "string", fields);
        creatBusinessField("心理测试量表", "string", fields);
        businessDTO.setFields(fields);

        return businessDTO;
    }

    /**
     * 个别人员
     * @return
     */
    public BusinessDTO cretaGBRY() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("个别人员");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("军衔", "string", fields);
        creatBusinessField("人员类别", "list", fields);
        creatBusinessField("上传时间", "date", fields);
        creatBusinessField("简要情况", "string", fields);
        creatBusinessField("在岗情况", "list", fields);
        creatBusinessField("三包一责任人", "string", fields);
        creatBusinessField("民族", "string", fields);
        creatBusinessField("政治面貌", "string", fields);
        creatBusinessField("文化程度", "string", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("户籍类型", "string", fields);
        creatBusinessField("入伍前经历", "string", fields);
        creatBusinessField("军人证件号", "string", fields);
        creatBusinessField("入伍年月", "date", fields);
        creatBusinessField("婚否", "string", fields);
        creatBusinessField("家庭情况", "string", fields);
        creatBusinessField("独生子女", "string", fields);
        creatBusinessField("联系人", "string", fields);
        creatBusinessField("联系地址", "string", fields);
        creatBusinessField("联系电话", "string", fields);
        creatBusinessField("备注", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 心理测试
     * @return
     */
    public BusinessDTO cretaXLCS() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("心理测试");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("测试结果", "list", fields);
        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 服刑人员
     * @return
     */
    public BusinessDTO cretaFXRY() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("服刑人员");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("罪名", "string", fields);
        creatBusinessField("服刑时间", "string", fields);
        creatBusinessField("服刑地点", "string", fields);
        creatBusinessField("服刑状态", "list", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 网络违规
     * @return
     */
    public BusinessDTO cretaWLWG() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("网络违规");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("主要问题", "string", fields);
        creatBusinessField("解决措施", "string", fields);
        creatBusinessField("解决时限", "string", fields);
        creatBusinessField("责任人", "string", fields);
        creatBusinessField("违规类型", "list", fields);
        creatBusinessField("卷宗材料", "number", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 自杀问题
     * @return
     */
    public BusinessDTO cretaZSWT() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("自杀问题");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("案件名称", "string", fields);
        creatBusinessField("时间", "date", fields);
        creatBusinessField("地点", "string", fields);
        creatBusinessField("方式", "string", fields);
        creatBusinessField("是否死亡", "list", fields);
        creatBusinessField("卷宗材料", "number", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 刑事案件
     * @return
     */
    public BusinessDTO cretaXSAJ() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("刑事案件");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("罪名", "list", fields);
        creatBusinessField("案件类型", "string", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("案件编号", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("民族", "string", fields);
        creatBusinessField("籍贯", "string", fields);
        creatBusinessField("出生日期", "date", fields);
        creatBusinessField("入伍日期", "date", fields);
        creatBusinessField("军衔", "string", fields);
        creatBusinessField("政治面貌", "string", fields);
        creatBusinessField("文化程度", "string", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("简要案情", "string", fields);
        creatBusinessField("立案时间", "date", fields);
        creatBusinessField("立案部门", "string", fields);
        creatBusinessField("主办人员", "string", fields);
        creatBusinessField("当前状况", "string", fields);
        creatBusinessField("监管措施", "string", fields);
        creatBusinessField("判决结果", "string", fields);
        creatBusinessField("执行情况", "string", fields);
        creatBusinessField("危害评估", "string", fields);
        creatBusinessField("卷宗材料", "number", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }




    /**
     * 敌社情-周边三资企业
     * @return
     */
    public BusinessDTO cretaSZQY() {
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("敌社情-周边三资企业");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("名称", "string", fields);
        creatBusinessField("性质", "string", fields);
        creatBusinessField("投资方所属国家（地区）", "string", fields);
        creatBusinessField("成立时间", "date", fields);
        creatBusinessField("经营方式及业务范围", "string", fields);
        creatBusinessField("执照登记号", "string", fields);
        creatBusinessField("经营状况", "string", fields);
        creatBusinessField("详细地址", "string", fields);
        creatBusinessField("附近部队", "string", fields);
        creatBusinessField("距离", "string", fields);
        creatBusinessField("国（境）外人员数量及国籍（地区）", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }

    /**
     * 敌社情-周边境外机构
     * @return
     */
    public BusinessDTO cretaJWJG() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("敌社情-周边境外机构");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("名称", "string", fields);
        creatBusinessField("机构性质", "string", fields);
        creatBusinessField("所属国家（地区）", "string", fields);
        creatBusinessField("详细地址", "string", fields);
        creatBusinessField("附近部队", "string", fields);
        creatBusinessField("距离", "string", fields);
        creatBusinessField("国（境）外人员数量及国籍（地区）", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }

    /**
     * 敌社情-周边境外常驻人员
     * @return
     */
    public BusinessDTO cretaCZRY() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("敌社情-周边境外常驻人员");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("所属国家（地区）", "string", fields);
        creatBusinessField("护照（身份证号）", "string", fields);
        creatBusinessField("职业", "string", fields);
        creatBusinessField("住房地址", "string", fields);
        creatBusinessField("住房性质", "string", fields);
        creatBusinessField("附近部队", "string", fields);
        creatBusinessField("是否为监控对象", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }

    /**
     * 敌社情-周边退役军人
     * @return
     */
    public BusinessDTO cretaTYJR() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("敌社情-周边境外常驻人员");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("籍贯", "string", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("居住详细地址", "string", fields);
        creatBusinessField("退役前部职别", "string", fields);
        creatBusinessField("现工作单位", "string", fields);
        creatBusinessField("附近部队", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 专家骨干
     * @return
     */
    public BusinessDTO cretaZJGG() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("专家骨干");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("专业特长", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("职业资格证书", "string", fields);
        creatBusinessField("资质等级", "string", fields);
        creatBusinessField("联系方式", "string", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("培训情况", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }


    /**
     * 军地协作
     * @return
     */
    public BusinessDTO cretaJDXZ() {

        String name = "通讯联络";
        Business business = businessRepository.findByName("通讯联络");
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return null;
        }
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("军地协作");
        businessDTO.setPid(business.getId());
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("身份证号", "string", fields);

        businessDTO.setFields(fields);

        businessService.save(businessDTO);

        return businessDTO;
    }


    /**
     * 通讯录
     * @return
     */
    public BusinessDTO cretaTXL() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("通讯录");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("电话", "string", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("内联|外联", "list", fields);
        creatBusinessField("人员标签", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("地址", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }




    /**
     * 创建只有名字的业务
     *
     * @return
     */
    public BusinessDTO cretaBusiness(String name,String routing) {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName(name);
        businessDTO.setRouting(routing);

        return businessDTO;
    }


    /**
     * 人员档案
     * @return
     */
    public BusinessDTO cretaRYDA() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("人员档案");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("姓名", "string", fields);
        creatBusinessField("曾用名", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("职务", "string", fields);
        creatBusinessField("电话", "string", fields);
        creatBusinessField("出生日期", "date", fields);
        creatBusinessField("入伍年月", "date", fields);
        creatBusinessField("性别", "list", fields);
        creatBusinessField("军衔", "list", fields);
        creatBusinessField("政治面貌", "string", fields);
        creatBusinessField("入党（团时间）", "date", fields);
        creatBusinessField("民族", "string", fields);
        creatBusinessField("籍贯", "string", fields);
        creatBusinessField("文化程度", "string", fields);
        creatBusinessField("人员标签", "list", fields);
        creatBusinessField("身份证号", "string", fields);
        creatBusinessField("家庭地址", "string", fields);
        creatBusinessField("家庭平均年收入", "string", fields);
        creatBusinessField("军人身份证件号", "string", fields);
        creatBusinessField("手机品牌", "string", fields);
        creatBusinessField("手机型号", "string", fields);
        creatBusinessField("军人驾驶证证号", "string", fields);
        creatBusinessField("车辆型号", "string", fields);
        creatBusinessField("车辆颜色", "string", fields);
        creatBusinessField("车牌号", "string", fields);


        businessDTO.setFields(fields);

        return businessDTO;
    }

    /**
     * 重要目标
     * @return
     */
    public BusinessDTO cretaZYMB() {

        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName("重要目标");
        List<BusinessField> fields = new ArrayList<>();
        creatBusinessField("目标名称", "string", fields);
        creatBusinessField("单位", "list", fields);
        creatBusinessField("地址", "string", fields);
        creatBusinessField("等级", "list", fields);
        creatBusinessField("负责人", "string", fields);

        businessDTO.setFields(fields);

        return businessDTO;
    }




    /**
     * 创建字段信息
     *
     * @param name
     * @param type
     * @return
     */
    public void creatBusinessField(String name, String type, List<BusinessField> fields) {

        BusinessField businessField = new BusinessField();
        businessField.setKey(name);
        businessField.setType(type);
        fields.add(businessField);
    }

    /**
     * 保存父级业务
     * @param name
     * @return
     */
    public Business addbBsiness(String name,List<BusinessDTO> business) {

        Business business1 = addbBsiness(name, business, null);

        return business1;
    }

    /**
     * 保存父级业务
     * @param name
     * @param business
     * @param invisible 是否在页面隐藏
     * @return
     */
    public Business addbBsiness(String name, List<BusinessDTO> business, Boolean invisible) {


        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setName(name);
        businessDTO.setRouting("businessGroup");
        businessDTO.setInvisible(invisible);

        Business save = businessService.save(businessDTO);

        if (CollUtil.isNotEmpty(business)) {
            business.stream().forEach(businessDTO1 -> {
                businessDTO1.setPid(save.getId());
                businessService.save(businessDTO1);
            });
        }


        return save;
    }


    /**
     * 初始化角色
     */
    public void initUser(String orgId) {

        String roleId = IdUtil.simpleUUID();
        //没有角色就创建默认角色
        Iterable<SysRole> all1 = roleRepository.findAll();
        if (CollUtil.isEmpty(all1)) {
            SysRole sysRole = new SysRole();
            sysRole.setId(roleId);
            sysRole.setCreateTime(System.currentTimeMillis());
            sysRole.setName(ADMIN);

            roleRepository.save(sysRole);
        }

        Iterable<Permission> allPermissions = permissionRepository.findAll();
        List<Permission> permissions = Lists.newArrayList(allPermissions);

        //为管理员追加最新权限
        User admin = userRepository.findByUserName("admin");
        if (admin != null) {
            admin.setPermissions(permissions);
            userRepository.save(admin);
        }

        //如果系统里面没有用户，就默认创建一个admin用户
        Iterable<User> all = userRepository.findAll();
        if (CollUtil.isEmpty(all)) {
            log.info("未找到默认用户，开始创建默认用户....");
            creatUser(orgId, "admin", permissions, roleId);
            creatUser(orgId, "admin2", permissions, roleId);
            creatUser(orgId, "admin3", permissions, roleId);


            log.info("默认用户创建成功，用户名：{},密码请咨询安装人员", "admin");
        }
    }

    /**
     * 创建用户
     * @param orgId
     * @param userName
     * @param permissions
     * @param roleId
     */
    public void creatUser(String orgId, String userName, List<Permission> permissions, String roleId) {

        User user = new User();
        user.setId(IdUtil.simpleUUID());
        user.setUserName(userName);
        user.setPassWord(encoder.encode("123456"));
        user.setRealName("系统管理员");
        Organization organization = organizationService.get(orgId);
        user.setOrgId(orgId);
        user.setOrg(organization.getOrgName());

        user.setIfEnable(true);
        user.setSysRoleId(roleId);

        user.setPermissions(permissions);
        user.setSysRoleName(ADMIN);
        user.setCreateTime(System.currentTimeMillis());
        userRepository.save(user);

    }


    /**
     * 创建政治考核权限
     */
    public void creatZZKHPermission() {

        String name = "政治考核";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }

        String pageaName = business.getId();

        String id = creatPagePermission(name, pageaName);
        saveBtn(id, pageaName, "query", name + "-查看");
        saveBtn(id, pageaName, "del", name + "-删除");
        saveBtn(id, pageaName, "export", name + "-导出");
        saveBtn(id, pageaName, "add", name + "-新增");
        saveBtn(id, pageaName, "query", name + "-查看");

    }

    /**
     * 创建敌情社情权限
     */
    public void creatDQSQPermission() {
        String name = "敌情社情";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }
        String pageName = business.getId();
        String id = creatPagePermission("敌情社情", pageName);
        saveBtn(id, pageName, "details", name + "-详情");
        saveBtn(id, pageName, "query", name + "-查看");

    }

    /**
     * 创建业务培训权限
     */
    public void creatYWPXPermission() {
        String name = "业务培训";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }

        String pageName = business.getId();

        String id = creatPagePermission("业务培训", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "del", name + "-删除");
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "details", name + "-详情");
        saveBtn(id, pageName, "download", name + "-下载");

    }


    /**
     * 创建文件通知权限
     */
    public void creatWJTZPermission() {
        String name = "文件通知";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }
        String pageName = business.getId();
        String id = creatPagePermission("文件通知", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "del", name + "-删除");
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "details", name + "-详情");
        saveBtn(id, pageName, "download", name + "-下载");
        saveBtn(id, pageName, "confirm", name + "-确认");

    }



    /**
     * 创建单位信息权限
     */
    public void creatDWXXPermission() {
        String name = "单位信息";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }
        String pageName = business.getId();
        String id = creatPagePermission("单位信息", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "edit", name + "-编辑");
        saveBtn(id, pageName, "del", name + "-删除");
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "details", name + "-详情");

    }

    /**
     * 创建常用模板权限
     */
    public void creatCYMBPermission() {

        String name = "常用模板";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }

        String pageName = business.getId();
        String id = creatPagePermission("常用模板", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "del", name + "-删除");
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "edit", name + "-编辑");
        saveBtn(id, pageName, "details", name + "-详情");

    }

    /**
     * 创建站内搜索权限
     */
    public void creatZNSSPermission() {

        String name = "站内搜索";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }
        String pageName = business.getId();
        String id = creatPagePermission("站内搜索", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "details", name + "-详情");

    }

    /**
     * 创建云搜索权限
     */
    public void creatYSSPermission() {

        String name = "云搜索";
        Business business = businessRepository.findByName(name);
        if (business == null) {
            log.warn("缺少业务：{}",name);
            return;
        }
        String pageName = business.getId();
        String id = creatPagePermission("云搜索", pageName);
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "details", name + "-详情");

    }


    /**
     * 创建业务管理权限
     */
    public void creatYWGLPermission() {

        String name = "业务管理";
        String pageName = PinyinUtil.getPinyin(name, "");
        String id = creatPagePermission("业务管理", pageName);
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "del", name + "-删除");

    }


    /**
     * 创建用户管理权限
     */
    public void creatYHGLPermission() {

        String name = "用户管理";
        String pageName = PinyinUtil.getPinyin(name, "");
        String id = creatPagePermission("用户管理", pageName);
        saveBtn(id, pageName, "add", name + "-新增");
        saveBtn(id, pageName, "query", name + "-查看");
        saveBtn(id, pageName, "edit", name + "-编辑");
        saveBtn(id, pageName, "del", name + "-删除");

    }


    /**
     * 创建页面权限
     *
     * @param name
     * @param pageName
     * @return
     */
    public String  creatPagePermission(String name, String pageName) {

        String pid = "";
        String ppid = "";
        List<Business> business = businessRepository.findAllByName(name);
        if (CollUtil.isNotEmpty(business)) {
            Business busines = null;

            //必须有父级id的
            if (business.size() > 1) {
                List<Business> collect = business.stream().filter(business1 -> {
                    return StringUtils.isNotBlank(business1.getPid());
                }).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(collect)) {
                    busines = collect.get(0);
                }
            } else if (business.size() == 1) {
                busines = business.get(0);
            }

            if (busines != null) {
                String pid1 = busines.getPid();
                ppid = md5.digestHex(busines.getId());  //直接用业务id的Md5做权限的id
                Business business1 = businessService.get(pid1);
                String id = business1.getId();
                pid = md5.digestHex(id);
            }

        }

        PermissionDTO permissionDTO = new PermissionDTO();
        permissionDTO.setType(1);   //菜单
        if (StringUtils.isBlank(pid)) {
            permissionDTO.setParentId("0");
        }else {
            permissionDTO.setParentId(pid);
        }

        permissionDTO.setName(name);
        permissionDTO.setPermission("page:" + pageName);
        Permission permission = permissionService.saveOrUpdate(permissionDTO, ppid);
        return permission.getId();
    }






    public void initPermissionCustom() {

        //创建所有的业务权限
        log.info("初始化系统资源");

        //处理自定义页面权限
        creatZZKHPermission();
        creatDQSQPermission();
        creatYWPXPermission();
        creatWJTZPermission();
        creatDWXXPermission();
        creatCYMBPermission();
        creatZNSSPermission();
        creatYSSPermission();

        //系统管理权限
        creatYWGLPermission();
        creatYHGLPermission();

        log.info("系统资源初始化完成");

    }

    /**
     * 保存按钮权限
     * @param pid   权限父级id
     * @param name  页面id
     * @param operation
     * @param operationName
     */
    public void saveBtn(String pid, String name, String operation, String operationName) {

        PermissionDTO permissionDTO = new PermissionDTO();
        String type = "btn:";
        permissionDTO.setType(2);   //按钮
        permissionDTO.setParentId(pid);
        permissionDTO.setName(operationName);
        permissionDTO.setPermission(type + name + ":" + operation);

        permissionService.saveOrUpdate(permissionDTO, null);
    }


}
